using System;
using System.Drawing;

using UtilityLibrary.General;

namespace UtilityLibrary.WinControls
{
	/// <summary>
	/// Summary description for DoubleBuffer.
	/// </summary>
	public class DoubleBuffer
	{
		#region Class Variables
		int bufferWidth;
		int bufferHeight;
		Bitmap surface;
		Graphics buffer;
		#endregion 

		#region Constructors
		public DoubleBuffer()
		{

		}
		
		public void Dispose() 
		{
			Cleanup();
		}
		#endregion
		
		#region Methods
		public Graphics RequestBuffer(int width, int height, Graphics g) 
		{
			if (width == bufferWidth && height == bufferHeight && buffer != null) 
			{
				return buffer;
			}

			Cleanup();
			surface = new Bitmap(width, height, g);
			buffer = Graphics.FromImage(surface);
			bufferWidth = width;
			bufferHeight = height;
			return buffer;
		}

		public void PaintBuffer(Graphics dest, int x, int y) 
		{
			dest.DrawImage(surface, x, y);
		}

		public void PaintBuffer(Graphics dest, Rectangle destRect, Rectangle sourceRect) 
		{
			dest.DrawImage(surface, destRect, sourceRect, GraphicsUnit.Pixel);
		}

		public void GDIPaintBuffer(Graphics dest, Rectangle destRect, Rectangle srcRect) 
		{
			GDIUtil.StrechBitmap(dest, destRect, srcRect, surface);
		}

		#endregion 
		
		#region Implementation
		private void Cleanup() 
		{
			if (buffer != null) 
			{
				buffer.Dispose();
				buffer = null;
			}
			if (surface != null) 
			{
				surface.Dispose();
				surface = null;
			}
		}

		#endregion
		
	}
	
}
